package app

import (
	"common/config"
	"common/rpc"
	"context"
	"fmt"
	"gate/router"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func Run(ctx context.Context) error {
	go func() {
		//实例化grpc客户端
		rpc.InitGateClient()
		//注册路由
		engine := router.InitRouter()
		if err := engine.Run(fmt.Sprintf(":%d", config.Conf.HttpPort)); err != nil {
			zap.S().Errorf("app gate start http service fail:%v", err)
		}
	}()
	stop := func() {
		time.Sleep(3 * time.Second)
		zap.S().Info("api gate do stop finally by signal")
	}
	//期望有一个优雅的启停，遇到中断 退出 终止 挂断
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGHUP)
	for {
		select {
		case <-ctx.Done():
			stop()
			//time out
			return nil
		case s := <-c:
			switch s {
			case syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT:
				stop()
				zap.S().Info("api gate quit")
				return nil
			case syscall.SIGHUP:
				stop()
				zap.S().Info("hang up! api gate quit")
				return nil
			default:
				return nil
			}
		}
	}
}
